package xyz.naokeziteng.leetcode;

/**
 * 268题：丢失的数字
 */
public class MissingNumber {

    /**
     * 借鉴桶排序
     * @param nums
     * @return
     */
    public static int missingNumber(int[] nums) {
        int[] result = new int[nums.length + 1];

        for (int i = 0; i < nums.length; i++) {
            result[nums[i]] = 1;
        }

        for (int j = 0; j < result.length; j++) {
            if (result[j] == 0) {
                return j;
            }
        }

        return -1;
    }

    public static int missingNumberV2(int[] nums) {
        int missingTotal = 0;
        int originTotal = (1 + nums.length) * nums.length / 2;
        for (int i = 0; i < nums.length; i++) {
            missingTotal += nums[i];
        }
        return originTotal - missingTotal;
    }

    public static int missingNumberV3(int[] nums) {
        int res = nums.length;
        for (int i = 0; i < nums.length; ++i){
            res ^= nums[i];
            res ^= i;
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {9, 6, 4, 2, 3, 5, 7, 0, 1};
        System.out.println(missingNumber(nums));
        System.out.println(missingNumberV2(nums));
        System.out.println(missingNumberV3(nums));
    }

}
